package org.wby.jwt.config.security;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/*
* 自定义权限拒绝处理类
* */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        try (ServletOutputStream servletOutputStream = response.getOutputStream();){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("success", false);
            resultMap.put("message", "抱歉，您没有访问权限");
            resultMap.put("code", 401);
            resultMap.put("timestamp", System.currentTimeMillis());
            resultMap.put("data", null);
            servletOutputStream.write(new Gson().toJson(resultMap).getBytes(StandardCharsets.UTF_8));
        }
    }


}
